package com.enjoy.udp.broadcast.bcside;

import com.enjoy.udp.broadcast.LogConst;
import com.enjoy.udp.broadcast.LogMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;

/**
 * Created by HP on 2019/7/15.
 * 日志广播端
 */
public class LogEventBroadcaster {
    private final EventLoopGroup group;
    private final Bootstrap bootstrap;

    public LogEventBroadcaster(InetSocketAddress destAddress){
        group=new NioEventLoopGroup();
        bootstrap=new Bootstrap();

        bootstrap.group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST,true)
                .handler(new LogEventEncoder(destAddress));
    }

    public void run() throws InterruptedException {
        //绑定channel
        Channel ch=bootstrap.bind(0).sync().channel();
        long count=0;
        for (;;){
            ch.writeAndFlush(new LogMsg(null,++count, LogConst.getLogInfo()));
            try {
                Thread.sleep(2000);
            }catch (InterruptedException e){
                Thread.sleep(2000);
                break;
            }
        }
    }


    public void stop() {
        group.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception {

        //创建并启动一个新的 UdpQuestionSide 的实例
        LogEventBroadcaster broadcaster = new LogEventBroadcaster(
                //表明本应用发送的报文并没有一个确定的目的地，也就是进行广播
                new InetSocketAddress("255.255.255.255",
                        LogConst.MONITOR_SIDE_PORT));
        try {
            broadcaster.run();
        }
        finally {
            broadcaster.stop();
        }
    }
}
